//
//  RequestClient.swift
//  Exchange
//
//  Created by rui on 2018/4/16.
//  Copyright © 2018年 common. All rights reserved.
//

import Foundation
import Alamofire

class RequestClient {
    var requestRecords: [Int:URLSessionTask] = [:]
    
    static let `default` = RequestClient()
    private init() {}
    typealias CallBack = (Response)->()
    
    
    func request(serviceIdentifier: Service,httpMethod: HTTPMethodType,params: [String: Any],methodName: String, timeoutInterval: TimeInterval=10,success: CallBack?, fail: CallBack?) -> Int {
        let request = RequestGenerator.generateReuqest(serviceIdentifier, httpMethod: httpMethod, params: params, methodName: methodName, timeoutInterval: timeoutInterval)

        var dataTask: DataRequest? = nil
        dataTask = Alamofire.request(request).responseJSON { (response) in
            var taskIdentifier = 0
            if let task = dataTask?.task {
                taskIdentifier = task.taskIdentifier
            }
            let res = Response(value: response.value, requestId: taskIdentifier, isCache: false, error: response.error)
            if response.result.isSuccess {
                if success != nil {
                    success!(res)
                }
            }else {
                if fail != nil {
                    fail!(res)
                }
            }
            self.requestRecords.removeValue(forKey: taskIdentifier)
        }
        guard let task = dataTask?.task else {
            return 0
        }
        self.requestRecords[task.taskIdentifier] = task
        return task.taskIdentifier
    }
    
    func cancelRequest(taskIdentifier: Int) {
        let task = self.requestRecords[taskIdentifier]
        task?.cancel()
        self.requestRecords.removeValue(forKey: taskIdentifier)
    }
    
    func cancelAll() {
        for task in self.requestRecords.values {
            task.cancel()
        }
        self.requestRecords.removeAll()
    }
}
